package com.wz.wiki.controller;

import com.wz.wiki.entity.req.UserLoginReq;
import com.wz.wiki.entity.req.UserQueryReq;
import com.wz.wiki.entity.req.UserResetPassWordReq;
import com.wz.wiki.entity.req.UserSaveReq;
import com.wz.wiki.entity.resp.CommonResp;
import com.wz.wiki.entity.resp.UserLoginResp;
import com.wz.wiki.entity.resp.UserQueryResp;
import com.wz.wiki.entity.resp.PageResp;
import com.wz.wiki.service.UserService;
import com.wz.wiki.utils.SnowFlake;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author 王哲
 * @Contact 1121586359@qq.com
 * @ClassName TestController.java
 * @create 2023年06月27日 下午10:02
 * @Description 用户控制层
 * @Version V1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private SnowFlake snowFlake;

    /**
     * 查询用户列表
     * @return
     */
    @GetMapping("/list")
    public CommonResp list(UserQueryReq req) {
        PageResp<UserQueryResp> users = userService.selectList(req);
        return CommonResp.success(users);
    }

    /**
     * 保存用户
     * @param req
     * @return
     */
    @PostMapping("/save")
    public CommonResp save(@RequestBody UserSaveReq req) {
        req.setPassword(DigestUtils.md5DigestAsHex(req.getPassword().getBytes()));
        userService.save(req);
        return CommonResp.success();
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/delete")
    public CommonResp delete(Long id) {
        userService.delete(id);
        return CommonResp.success();
    }

    /**
     * 重置密码
     * @param req
     * @return
     */
    @PostMapping("/resetPassword")
    public CommonResp resetPassword(@RequestBody UserResetPassWordReq req) {
        req.setPassword(DigestUtils.md5DigestAsHex(req.getPassword().getBytes()));
        userService.resetPassword(req);
        return CommonResp.success();
    }

    /**
     * 登录
     * @param req
     * @return
     */
    @PostMapping("/login")
    public CommonResp login(@RequestBody UserLoginReq req) {
        req.setPassword(DigestUtils.md5DigestAsHex(req.getPassword().getBytes()));
        UserLoginResp userLoginResp = userService.login(req);
        // 生成一个token，保存用户登录状态
        String token = String.valueOf(snowFlake.nextId());
        redisTemplate
                .opsForValue()
                .set(token, userLoginResp,3600, TimeUnit.SECONDS);
        userLoginResp.setToken(token);
        return CommonResp.success(userLoginResp);
    }

    /**
     * 退出登录
     */
    @GetMapping("/logout/{token}")
    public CommonResp logout(@PathVariable String token) {
        redisTemplate.delete(token);
        return CommonResp.success();
    }

}
